<template>
  <div class="note-edit">
    <top-header></top-header>

    <div>
      <div class="form" v-fullheight="{ excessIds: ['btn-div'] }">
        <div class="err-msg" :class="{ 'err-msg-show': errMsgShow }">
          <span>{{ errMsg }}</span>
          <span class="iconfont iconcha" @click="errMsgShow = false"></span>
        </div>
        <ul>
          <li :class="{ readonly: projectId }" @click="projectId ? false : changeProjectShow('noteProjectPopup')" class="bottom-line">
            <span class="title">关联项目</span>
            <span class="placeholder" v-show="!form.project || !form.project.guid">请选择</span>
            <span class="info" v-show="form.project && form.project.guid">{{ form.project.name }}</span>
            <i class="iconfont iconshouqi"></i>
          </li>
          <li @click="changeProjectShow('noteBusinessPopup')" class="bottom-line">
            <span class="title">关联业务</span>
            <span class="placeholder" v-show="!form.project || !form.business.guid">请选择</span>
            <span class="info" v-show="form.project && form.business.guid">{{ form.business.name }}</span>
            <i class="iconfont iconshouqi"></i>
          </li>
          <li @click="changeProjectShow('noteStakeholderPopup')" class="bottom-line">
            <span class="title">关联干系人</span>
            <span class="placeholder" v-show="!form.stakeholderList || form.stakeholderList.length === 0">请选择</span>
            <span class="info" v-show="form.stakeholderList && form.stakeholderList.length > 0">
              <template v-if="form.stakeholderList">
                <i v-for="(item, key) in form.stakeholderList" :key="key">{{ key === 0 ? "" : "," }}{{ item.name }}</i>
              </template>
            </span>
            <i class="iconfont iconshouqi"></i>
          </li>
          <li class="bottom-line">
            <span class="title">便签内容</span>
            <van-field class="info" v-model="form.content" rows="4" autosize type="textarea" placeholder="这是一段长文本" />
          </li>
        </ul>
      </div>

      <div class="btn-div top-line" id="btn-div">
        <div @click="$router.go(-1)">取消</div>
        <div @click="submit">确定</div>
      </div>
    </div>

    <!-- 关联项目选择框 -->
    <note-project-popup :form-data.sync="form.project" ref="noteProjectPopup"></note-project-popup>
    <!-- 关联项目选择框 -->
    <note-business-popup :form-data.sync="form.business" :project="form.project" ref="noteBusinessPopup"></note-business-popup>
    <!-- 关联干系人选择框 -->
    <note-stakeholder-popup :form-data.sync="form.stakeholderList" :project="form.project" ref="noteStakeholderPopup"></note-stakeholder-popup>
  </div>
</template>

<script lang="ts">
import { Component, Watch } from "vue-property-decorator";
import { Button, Field, Popup, Checkbox, CheckboxGroup, CellGroup, Cell } from "vant";
import Base from "@/utils/base";
import TopHeader from "@/components/TopHeader.vue";
import Api from "@/api";
import NoteProjectPopup from "./ProjectPopup.vue";
import NoteBusinessPopup from "./BusinessPopup.vue";
import NoteStakeholderPopup from "./StakeholderPopup.vue";

@Component({
  name: "NoteEdit",
  components: {
    TopHeader,
    NoteProjectPopup,
    NoteBusinessPopup,
    NoteStakeholderPopup,
    VanButton: Button,
    VanField: Field,
    VanPopup: Popup,
    VanCheckbox: Checkbox,
    VanCheckboxGroup: CheckboxGroup,
    VanCellGroup: CellGroup,
    VanCell: Cell
  }
})
export default class NoteEdit extends Base {
  private show = false;
  private errMsg = "";
  private errMsgShow = false;
  private guid = "";
  private detail: any = {};
  // projectId存在，代表从项目概况进入，便签的编辑和新增，关联项目只读
  private projectId = "";
  private projectName = "";

  private form = {
    project: {
      name: "",
      guid: ""
    },
    business: {
      name: "",
      guid: ""
    },
    stakeholderList: [] as any[],
    content: ""
  };

  @Watch("form.project")
  watchFormProject(newValue: any, oldValue: any) {
    const newGuid = newValue && newValue.guid ? newValue.guid : "";
    const oldGuid = oldValue && oldValue.guid ? oldValue.guid : "";
    if (!newGuid || (oldGuid && newGuid !== oldGuid)) {
      this.$set(this.form, "business", {});
      this.$set(this.form, "stakeholderList", []);

      (this.$refs["noteBusinessPopup"] as any).clearData();
      (this.$refs["noteStakeholderPopup"] as any).clearData();
    }
  }

  private created() {
    this.projectId = (this.$route.query.projectId ? this.$route.query.projectId : "") as string;
    this.projectName = decodeURIComponent((this.$route.query.projectName ? this.$route.query.projectName : "") as string);

    if (this.projectId) {
      this.$set(this.form, "project", { name: this.projectName, guid: this.projectId });
    }

    this.guid = this.$route.query.guid ? (this.$route.query.guid as string) : "";
    if (this.guid) {
      this.$cPromise.all([this.getNoteDetai()]);
    }
  }

  private async getNoteDetai() {
    const res = await Api.GetNoteDetail(this.guid);
    if (res && res.code) {
      this.detail = res.data;

      this.form = {
        project: {
          name: res.data.projectName,
          guid: res.data.projectId
        },
        business: {
          name: res.data.businessName,
          guid: res.data.businessId
        },
        stakeholderList: Array.from(res.data.stakeholderList, (item: any) => {
          return { guid: item.stakeholderId, name: item.stakeholderName };
        }),
        content: res.data.content
      };
    }
    return res;
  }

  private async changeProjectShow(ref: string) {
    if (!this.form.project.guid && ref === "noteBusinessPopup") {
      this.errMsg = "请先选择关联项目，再选择关联标段";
      this.errMsgShow = true;
    } else if (!this.form.project.guid && ref === "noteStakeholderPopup") {
      this.errMsg = "请先选择关联项目，再选择关联干系人";
      this.errMsgShow = true;
    } else {
      (this.$refs as any)[ref].changeShow();
      this.errMsgShow = false;
    }
  }

  private get check() {
    if (!this.form.content) {
      this.errMsg = "请输入便签内容";
      return false;
    }
    return true;
  }

  private async submit() {
    if (!this.check) {
      this.errMsgShow = true;
    } else {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "正在加载..."
      });
      const res = await Api.SaveNoteDetail(this.submitParams);
      toast.clear();
      if (res.code === 200) {
        this.$dialog
          .alert({
            message: "保存成功"
          })
          .then(() => {
            this.$router.go(-1);
          });
      } else {
        this.$toast({
          message: res.code === 500 ? "系统异常" : res.msg
        });
      }
    }
  }

  /**
   * 提交接口参数
   */
  private get submitParams() {
    const _return = {
      projectId: this.form.project.guid,
      projectName: this.form.project.name,
      businessId: this.form.business.guid,
      stakeholderId: Array.from(this.form.stakeholderList, (item: any) => item.guid).join(","),
      guid: this.guid,
      content: this.form.content
    };

    return _return;
  }
}
</script>

<style lang="less" scoped>
.note-edit {
  background-color: white;
  .form {
    // height: calc(100% - 50px);

    .err-msg {
      background-color: #fef0f0;
      color: #d5001c;
      font-size: 12px;
      height: 0;
      transition-duration: 0.5s;
      overflow: hidden;
      padding-left: 12px;
      line-height: 35px;
      display: flex;
      justify-content: space-between;
    }

    .err-msg-show {
      height: 35px;
    }

    .iconcha {
      font-size: 20px;
      padding: 0 12px;
    }

    ul {
      padding-left: 12px;
    }

    li {
      display: flex;
      padding: 13px 0;
      position: relative;

      &.readonly {
        .info {
          color: #999999;
        }
        .iconshouqi {
          display: none;
        }
      }
    }
    .title {
      font-size: 16px;
      width: 120px;
    }
    .placeholder {
      color: #797f89;
    }
    .info {
      flex: 1;
      padding: 0px 40px 0px 0px;
      i {
        font-style: normal;
      }
    }
    .iconshouqi {
      position: absolute;
      top: 50%;
      margin-top: -7px;
      right: 13px;
      color: #cccccc;
      font-size: 14px;
      transform: rotate(-90deg);
    }
  }

  .btn-div {
    display: flex;
    color: #76b2fb;
    font-size: 16px;
    position: relative;
    &::after {
      position: absolute;
      content: "";
      height: 15px;
      border-right: 1px solid #cccbcb;
      top: 17px;
      left: 50%;
      transform: scaleX(0.5);
    }
    & > div {
      width: 50%;
      text-align: center;
      line-height: 50px;
      &:active {
        opacity: 0.5;
      }
    }
  }
}
</style>
